package com.dhj.yygh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dhj.yygh.enums.OrderStatusEnum;
import com.dhj.yygh.enums.RefundStatusEnum;
import com.dhj.yygh.mapper.RefundMapper;
import com.dhj.yygh.model.order.PaymentInfo;
import com.dhj.yygh.model.order.RefundInfo;
import com.dhj.yygh.service.RefundService;
import org.springframework.stereotype.Service;

import javax.xml.ws.ServiceMode;
import java.util.Date;

/**
 * 支付退款 Service
 */
@Service
public class RefundServiceImpl extends ServiceImpl<RefundMapper, RefundInfo> implements RefundService {

    /**
     * 保存退款记录
     *
     * @param paymentInfo 支付记录对象
     * @return 返回保存的退款记录
     */
    @Override
    public RefundInfo saveRefundInfo(PaymentInfo paymentInfo) {

        QueryWrapper<RefundInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", paymentInfo.getOrderId());
        wrapper.eq("payment_type", paymentInfo.getPaymentType());

        RefundInfo refundInfo = baseMapper.selectOne(wrapper);

        // 退款记录存在，直接返回该记录
        if (null != refundInfo) {
            return refundInfo;
        }

        // 保存交易记录
        refundInfo = new RefundInfo();
        refundInfo.setCreateTime(new Date());
        refundInfo.setOrderId(paymentInfo.getOrderId());
        refundInfo.setPaymentType(paymentInfo.getPaymentType());
        refundInfo.setOutTradeNo(paymentInfo.getOutTradeNo()); // 对外业务编号
        refundInfo.setRefundStatus(RefundStatusEnum.UNREFUND.getStatus()); // 退款状态
        refundInfo.setSubject(paymentInfo.getSubject()); // 交易内容
        refundInfo.setTotalAmount(paymentInfo.getTotalAmount()); // 对应订单的金额

        return baseMapper.insert(refundInfo) > 0 ? refundInfo : null;
    }
}
